﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TimKen.DataAccess;
using TimKen.BussLogic;
using System.Data;
using TimKen.DataEntity;
using TimKen.App;

namespace TimKen.Web.Shop
{
    public partial class CommitOrders : TimKen.App.WebPage
    {

        AddressDAO dao = new AddressDAO();
        protected UserAccountManager userM = new UserAccountManager();
        protected CustomerManager customerM = new CustomerManager();
        LinkManManager LinkM = new LinkManManager();
        AddressManager addressM = new AddressManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (CurrentUserName != null && CurrentUserName != "")
                {
                    bind();
                    BindTransType();
                }
                else
                {
                    Alert("您必须登录！", "../Index.aspx");
                }
            }

        }
        public void bind()
        {
            DataTable dt = dao.GetAddressByUser(CurrentUserName);
            this.Rp_Address.DataSource = dt;
            this.Rp_Address.DataBind();
        }

        /// <summary>
        /// 绑定运输方式
        /// </summary>
        protected void BindTransType()
        {
            TimKen.BussLogic.TransTypeManager ttM = new TimKen.BussLogic.TransTypeManager();
            System.Data.DataSet transDS = ttM.GetList(LanguageWhereStr);
            yhlxid.DataSource = transDS;
            yhlxid.DataBind();
            yhlxid.Items.FindByValue("9").Selected = true;
        }

        protected void lk_Add_Click(object sender, EventArgs e)
        {
            if (this.address.Value != "" && this.name.Value != "")
            {
                CommonAddress ad = new CommonAddress();
                string id = dao.isExitsAddress(this.address.Value, this.name.Value);
                if (id != "")
                {
                    ad.Phone = this.phone.Value;
                    ad.Telephone = this.pnum.Value;
                    ad.PostalCode = this.code.Value;
                    ad.Remark = this.remarks.Value;
                    ad.UserName = CurrentUserName;
                    ad.Address = this.address.Value;
                    ad.Consignee = this.name.Value;
                    ad.Email = this.email.Value;
                    ad.ID = Convert.ToInt32(id);
                    bool bo = dao.UpdateAddress(ad);
                    if (bo)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "tan", "<script>add(1);</script>");

                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "tan", "<script>add(2);</script>");
                    }
                    bind();
                }
                else
                {
                    ad.Phone = this.phone.Value;
                    ad.Telephone = this.pnum.Value;
                    ad.PostalCode = this.code.Value;
                    ad.Remark = this.remarks.Value;
                    ad.UserName = CurrentUserName;
                    ad.Address = this.address.Value;
                    ad.Consignee = this.name.Value;
                    ad.Email = this.email.Value;
                    bool bo = dao.InserAddress(ad);
                    if (bo)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "tan", "<script>add(1);</script>");
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "tan", "<script>add(2);</script>");
                    }
                    bind();
                }
            }

        }
        protected void rd_CheckChanged(object sender, EventArgs e)
        {
            RadioButton rad = sender as RadioButton;
            RepeaterItem rt = rad.NamingContainer as RepeaterItem;
            HiddenField hif = rt.FindControl("Rd_id") as HiddenField;
            int num = rt.ItemIndex;
            Repeater rp = rt.NamingContainer as Repeater;
            for (int i = 0; i < rp.Items.Count; i++)
            {
                if (i != num)
                {
                    RadioButton radt = rp.Items[i].FindControl("rd_ck") as RadioButton;
                    if (radt.Checked == true)
                    {
                        radt.Checked = false;
                    }
                }
            }
            DataTable dt = dao.GetAddressByid(hif.Value);
            if (dt != null && dt.Rows.Count > 0)
            {
                this.phone.Value = dt.Rows[0]["Phone"].ToString();
                this.pnum.Value = dt.Rows[0]["Telephone"].ToString();
                this.code.Value = dt.Rows[0]["PostalCode"].ToString();
                this.remarks.Value = dt.Rows[0]["Remark"].ToString();
                this.address.Value = dt.Rows[0]["Address"].ToString();
                this.name.Value = dt.Rows[0]["Consignee"].ToString();
                this.email.Value = dt.Rows[0]["Email"].ToString();
            }


        }
        protected void Rp_Address_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                bool bo = dao.DeleteAddress(e.CommandArgument.ToString());
                if (bo)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tan", "<script>del(1);</script>");
                    bind();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tan", "<script>del(2);</script>");
                }
            }
        }

        public TimKen.DataEntity.Order CheckedOrder(string userName)
        {
            //1.数量检验，
            //  循环购物车中的每一项，计算产品的可出货额和购买数量：
            //   |--数量不足-->返回false，提示产品名称+不足信息--||结束
            //   |--数量足够
            //       |--2.信用检查
            //            1)从usererName获取User信息再获取到相应的Customer信息
            //            2)计算出Customer的可用信用额度
            //            3)计算userName获取购物车中的含税总价
            //                |--含税总价<=可用信用额度--->orderState =1 Pass，返回true--||结束
            //                |--含税总价>可用信用额度
            //                    |--4)检查系统设置，是否必须条件
            //                          |--必须-->返回false--||结束 
            //                          |--非必须-->orderState =2 For B1 Check 返回true--||结束 

            ShopCartSet cartM = this.ShopCart;
            ProductManager ptM = new ProductManager();
            Dictionary<string, ShopCartItem> shopItems = cartM.GetItems;
            // DataSet cartLists = cartM.GetList(" UserName = '" + userName + "'");
            TimKen.DataEntity.Order order = new TimKen.DataEntity.Order();//订单
            List<OrderItem> orderItems = new List<OrderItem>();
            //获取客户信息
            CustomerManager ctmM = new CustomerManager();
            UserAccountManager userM = new UserAccountManager();
            UserAccount user = userM.GetModel(userName);
            ProductDAO dao = new ProductDAO();
            Customer customer = ctmM.GetModel(userM.GetModel(userName).CustomerID.Value);
            int maxShipDays = 0;
            for (int i = 0; i < shopItems.Count; i++)
            {
                TimKen.DataEntity.Product product = ptM.GetModel(dao.getIDByNo(shopItems.ElementAt(i).Value.Project.ProjectId.ToString()));
                if (product == null)
                    continue;
                if (CheckFrozen(product.Freeze, product.FreezeFrom, product.FreezeTo))
                    continue;
                //客户购买量
                decimal number = decimal.Parse(shopItems.ElementAt(i).Value.Count.ToString());

                ////-----检核库存-----
                ////商品可用库存

                ////2009-3-30 修改成库存为空也可以下单
                //decimal pInv = product.InvQty - product.BookedQty.Value;
                //if (number > pInv)
                //{
                //    ValidMessage = product.ItemCode + GetLangString("NotEnoughInventory");
                //    return null;
                //}

                //    //-----保存OrderItem-----
                OrderItem orderItem = new OrderItem();

                //修改by miaozy at  090305 价格加入多币种
                PPrice price = ptM.GetProductBasePrice(product.ProductID, customer.CustomerID);
                //if (price.Price == 0)
                //{
                //    ValidMessage = GetLangString("Price0Product");
                //    return null;
                //}
                orderItem.BasicPrice = price.Price;
                orderItem.FinalPrice = ptM.GetProductPriceByCustomer(product, customer.CustomerID, number);
                orderItem.ItemCode = product.ItemCode;
                orderItem.ProductID = product.ProductID;
                orderItem.Quantity = number;
                orderItem.Weight = product.Weight;
                orderItem.WeightUnit = product.WeightUnit;
                orderItem.TotalWeight = product.Weight * number;
                orderItem.BaseAmount = orderItem.FinalPrice * orderItem.Quantity;
                orderItem.Unit = product.SalesUnit;
                ///用BarCode字段来存储产品名称，即产品型号
                PDescriptionManager pdm = new PDescriptionManager();
                PDescription description = pdm.GetModel(product.ProductID, 1);
                orderItem.BarCode = description.Name;
                //在订单单身中添加折扣率
                if (orderItem.BasicPrice != 0)
                    orderItem.Discount = orderItem.FinalPrice / orderItem.BasicPrice;
                else
                    orderItem.Discount = 1;

                if (customer.TaxRate == 0)
                {
                    orderItem.TaxAmount = 0;
                    orderItem.TaxRate = 0;
                }
                else
                {
                    orderItem.TaxAmount = orderItem.BaseAmount * product.TaxRate.Value;
                    orderItem.TaxRate = product.TaxRate.Value;
                }
                orderItem.TotalAmount = orderItem.BaseAmount + orderItem.TaxAmount;
                //-----计算order的未含税总额，含税总额，总税额-----
                order.BaseAmount += orderItem.BaseAmount;
                order.TotalAmount += orderItem.TotalAmount;
                order.TaxAmount += orderItem.TaxAmount;

                orderItems.Add(orderItem);
                maxShipDays = product.ShipDays > maxShipDays ? product.ShipDays : maxShipDays;
            }

            //-----信用检测-----

            //客户可使用信用额度  修改by miaozy
            decimal balance = customer.CreditLimit.Value + customer.CurrentAccountBalance.Value - customer.ECOrdersBalance == null ? 0 : customer.ECOrdersBalance.Value;

            //购物含税总价未超过可使用额度
            bool CheckBefore = SystemConfigManager.SystemConfig.CreditCheck;

            if (order.TotalAmount > balance)
            {
                //信用检测为必要关卡
                if (CheckBefore)
                {
                    order.CheckFlag = false;
                    ValidMessage = GetLangString("NotEnoughAmount");
                    return null;
                }
                else
                {
                    //信用检测非关卡
                    //设置状态为for B1 Check
                    order.OrderStatus = OrderStatus.ForB1Check;
                }
            }
            else
            {
                order.OrderStatus = OrderStatus.Pass;
                //设置状态为Pass

            }
            order.MaxShipDays = maxShipDays;
            order.Currency = customer.Currency;
            order.Rate = customer.TaxRate.Value;
            order.CardCode = customer.CardCode;
            order.ApproveType = CheckBefore ? 1 : 0;
            order.OrderItems = orderItems;
            order.TaxClassID = customer.TaxClassID;
            order.SalesPersonCode = customer.SalesPersonCode;
            order.Mobile = customer.Mobile;
            order.Fax = customer.Fax;
            order.Email = customer.Email;
            order.CustomerID = customer.CustomerID;
            return order;
        }
        public static bool CheckFrozen(bool Frozen, object FrozenFrom, object FrozenTo)
        {
            bool IsFrozen = true;
            if (Frozen)
            {
                if (FrozenFrom != null && FrozenFrom.ToString() != "")
                {
                    DateTime freezeFrom = Convert.ToDateTime(FrozenFrom);
                    if (freezeFrom > DateTime.Now)
                    {
                        IsFrozen = false;
                    }
                }
                if (FrozenTo != null && FrozenTo.ToString() != "")
                {
                    DateTime freezeTo = Convert.ToDateTime(FrozenTo);
                    if (freezeTo < DateTime.Now)
                    {
                        IsFrozen = false;
                    }
                }
            }
            else
            {
                IsFrozen = false;
            }
            return IsFrozen;
        }
        protected void img_add_Click(object sender, ImageClickEventArgs e)
        {
            //CommonAddress add = new CommonAddress();
            //add.Phone = this.phone.Value;
            //add.Telephone = this.pnum.Value;
            //add.PostalCode = this.code.Value;
            //add.Remark = this.remarks.Value;
            //add.Address = this.address.Value;
            //add.Consignee = this.name.Value;
            //add.Email = this.email.Value;
            //add.Date = this.txt_Date.Value;
            //add.ShipType =Convert.ToInt32(this.ddlTransType.SelectedValue);

            //Session["address"] = add;
            OrderManager orderM = new OrderManager();
            TimKen.DataEntity.Order order = CheckedOrder(CurrentUserName);
            if (order == null)
            {
                Alert(this.sValidMessage);
            }
            else
            {
                TimKen.DataEntity.Customer customer = customerM.GetModel(userM.GetModel(CurrentUserName).CustomerID.Value);
                order.Creator = CurrentUserName;
                order.OrderType = TimKen.DataEntity.OrderType.Order;
                order.ShipType = int.Parse(yhlxid.SelectedValue);
                if (order.ShipType != 1)
                    order.ShipToCode = "";
                else
                    order.ShipToCode = "0";
                string newaddresscode = string.Empty;
                if (order.ShipToCode != "0")
                {

                    newaddresscode = "newaddress" + DateTime.Now.ToString("yyyyMMddmmss");
                    order.ShipToCode = newaddresscode;
                    order.ShipAddress = this.address.Value;
                    //保存收货地址
                    AddressManager am = new AddressManager();
                    Address address = new Address();
                    address.AddressCode = order.ShipToCode;
                    address.AdresType = "S";
                    address.Street = order.ShipAddress;
                    address.LanguageID = LanguageID;
                    address.CardCode = customer.CardCode;
                    address.Block = "";
                    address.Building = "";
                    address.City = "";
                    address.Country = "";
                    address.County = "";
                    address.State = "";
                    address.ZipCode = "";
                    address.ContactPerson = this.name.Value;
                    address.Phone = this.phone.Value;
                    address.GNum = this.pnum.Value;
                    am.Add(address);
                }
                if (this.yhlxid.SelectedValue == "1" && this.Rad_2.Checked == true)
                {
                    //保存收货地址
                    AddressManager am = new AddressManager();
                    Address address = new Address();
                    address.AddressCode = "newaddress" + DateTime.Now.ToString("yyyyMMddmmss");
                    address.AdresType = "B";
                    address.Street = this.Baddress.Value;
                    address.LanguageID = LanguageID;
                    address.CardCode = customer.CardCode;
                    address.Block = "";
                    address.Building = "";
                    address.City = "";
                    address.Country = "";
                    address.County = "";
                    address.State = "";
                    address.ZipCode = this.Bcode.Value;
                    address.Phone = this.Bphone.Value;
                    address.ContactPerson = this.Blxr.Value;
                    am.Add(address);
                    order.BillToCode = address.AddressCode;
                    order.BillAddress = address.Street;
                    order.ShipToCode = "0";
                    order.ShipAddress = "";
                }
                else if (this.yhlxid.SelectedValue == "1" && this.Rad_1.Checked == true)
                {
                    order.BillToCode = "0";
                    order.BillAddress = "";
                    order.ShipToCode = "0";
                    order.ShipAddress = "";
                }
                else if (this.yhlxid.SelectedValue == "9" && this.Rad_1.Checked == true)
                {
                    AddressManager am = new AddressManager();
                    Address address = new Address();
                    address.AddressCode = order.ShipToCode;
                    address.AdresType = "B";
                    address.Street = order.ShipAddress;
                    address.LanguageID = LanguageID;
                    address.CardCode = customer.CardCode;
                    address.Block = "";
                    address.Building = "";
                    address.City = "";
                    address.Country = "";
                    address.County = "";
                    address.State = "";
                    address.ZipCode = "";
                    address.ZipCode = this.code.Value;
                    address.Phone = this.phone.Value;
                    address.ContactPerson = this.name.Value;
                    am.Add(address);
                    order.BillToCode = address.AddressCode;
                    order.BillAddress = address.Street;
                    order.ContactPerson = this.name.Value;
                    order.Telephone = this.pnum.Value;
                    order.Mobile = this.phone.Value;
                    order.Email = this.email.Value;
                    order.Remark = this.remarks.Value;
                }
                else if (this.yhlxid.SelectedValue == "9" && this.Rad_2.Checked == true)
                {
                    AddressManager am = new AddressManager();
                    Address address = new Address();
                    address.AddressCode = "newaddress" + DateTime.Now.ToString("yyyyMMddmmss");
                    address.AdresType = "B";
                    address.Street = this.Baddress.Value;
                    address.LanguageID = LanguageID;
                    address.CardCode = customer.CardCode;
                    address.Block = "";
                    address.Building = "";
                    address.City = "";
                    address.Country = "";
                    address.County = "";
                    address.State = "";
                    address.ZipCode = this.Bcode.Value;
                    address.Phone = this.Bphone.Value;
                    address.ContactPerson = this.Blxr.Value;
                    am.Add(address);
                    order.BillToCode = address.AddressCode;
                    order.BillAddress = address.Street;
                    order.ContactPerson = this.name.Value;
                    order.Telephone = this.pnum.Value;
                    order.Mobile = this.phone.Value;
                    order.Email = this.email.Value;
                    order.Remark = this.remarks.Value;
                }

                //}
                //else
                //{
                //    order.ShipAddress = addressM.GetAddressString(addressM.GetModel(order.ShipToCode, "S", customer.CardCode));

                //}

                //判断联系人,送货地址,帐单地址不能为空
                if (this.name.Value.Trim() == "")
                {
                    Alert(GetLangString("x_LinkManNotAllowBlank"));
                    return;
                }
                if (order.ShipToCode.Trim() == "" && order.ShipType != 1)
                {
                    Alert(GetLangString("x_ShipAddressNotAllowBlank"));
                    return;
                }
                //如果自提的话,期望交货日期不能够为空
                if (this.txt_Date.Value.Trim() == "")
                {
                    Alert(GetLangString("x_ExpectDateNotAllowBlank"));
                    return;
                }
                if (!TypeParse.IsValidDate(this.txt_Date.Value.Trim()))
                {
                    Alert(GetLangString("x_ExpectDateNotValid"));
                    return;
                }
                //任何订单都需要后台审核...by miaozy at   2009.9.7
                //
                //如果运输方式非自提,则要等待EC管理员后台审核.否则直接通过
                //if (order.ShipType != 1)
                //{
                //    //设置状态为Pass
                //    order.OrderStatus = OrderStatus.ForFirstBridgeSOFreightConfirm;
                //}

                order.OrderStatus = OrderStatus.ForFirstBridgeSOFreightConfirm;
                order.ExpectDate = Convert.ToDateTime(this.txt_Date.Value.Trim());
                order.ContractTerm = Tools.GetDefualtOrderTerm();
                if (order.ShipType == 1)
                {
                    order.Freight = 0;
                }

                //if (order.ShipToCode.Equals(newaddresscode))
                //{

                //}
                order.Email = this.email.Value;
                string orderID = null;
                orderID = orderM.Add(order);
                Tools.SendOrderCreateEmail(orderID);
                try
                {
                    Response.Redirect("/order/OrderInfos.aspx?OrderID=" + orderID, false);
                }
                catch (System.Threading.ThreadAbortException)
                {

                }
                catch (Exception ex)
                {
                    if (ex.Message == "not enough Inventory\r\n1")
                    {
                        Alert(GetLangString("NotEnoughInventory"));
                        return;
                    }
                    Clogs.LogError("提交订单出错", ex);
                    Alert(GetLangString("Error"));
                    throw ex;

                }


            }
        }

    }
}